//
//  ZQBaseTabBarController.swift
//  Timor微博
//
//  Created by 周周旗 on 2019/2/26.
//  Copyright © 2019 ZQ. All rights reserved.
//

import UIKit

class ZQMainViewController: UITabBarController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpChildControllers()
        setupComposeButton()
        
        delegate = self
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(n:)), name: NSNotification.Name(rawValue: WBUserLoginNotifaction), object: nil)
    }
    
    deinit {
        //注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 设置屏幕横竖屏显示界面
    /**
     portrait :竖屏
     landscap :横屏
     - 使用代码控制设备方向，好处是可以在需要横屏时做单独处理
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向！
     - 写在 ZQMainViewController 里的原因，是因为视频播放一般是 `modal` 展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        
        return .portrait;
    }
    
    // MARK:监听方法
    @objc private func userLogin(n: Notification){
        print("用户登录通知\(n)")
        //展现登录控制器 - modal 方法通常和UINavigationController连用，方便返回
        let nv = UINavigationController.init(rootViewController: ZQOAuthViewController())
        present(nv, animated: true, completion: nil)
    }
    
    //FIXME:没有实现
    // private:保证该方法只能在本类内部进行调用
    // @objc private :允许这个函数在`运行时`通过 OC 的 `消息机制` 被调用！
    @objc private func composeStaus(){
        print("撰写微博")
    }
    
    // MARK:私有控件
    private lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
}

// MARK: - UITabBarControllerDelegate
extension ZQMainViewController:UITabBarControllerDelegate{
    
    /// 将要选择TabBarItem
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        //1. 获取当前的viewController index
        let idx = (children as NSArray).index(of: viewController)
        //2.判断当前索引为首页，index也为首页
        if selectedIndex == 0 && idx == selectedIndex{
            print("点击首页")
            //3. 让首页表格滚动到顶部
            //3.1 控制器获取
            let nv = children[idx] as! UINavigationController
            let vc = nv.children[0] as! ZQHomeViewController
            //3.2 滚动到顶部
            vc.tableview?.setContentOffset(CGPoint(x: 0, y: -ZQNavigationBar.NaviBarStatusBarHeight), animated: true)
            //3.3 刷新表格
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.5) {
                vc.loadData()
            }
        }
        //判断目标控制器是否为UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}

// extension 类似于OC中的catory(分类),只添加方法不添加属性。在swift中还可以用来进行`分块`代码.
// 可以把功能相近的函数放在一起，方便代码维护
// MARK - 设置界面
extension ZQMainViewController{
    
    /// 编写中间按钮
    private func setupComposeButton(){
        tabBar.addSubview(composeButton)
        //计算按钮的宽度
        let count = CGFloat(children.count)
        
        let w = tabBar.bounds.width/count
        //1< `inset` 正数向内缩进，负数向外扩展
        //2< 如果想中间控件突出tabbar 只需要将 `dy` 设为负值
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeButton.addTarget(self, action: #selector(composeStaus), for: .touchUpInside)
    }
    
    
    /// 设置所有子控制器
    private func setUpChildControllers(){
        //1. 从网络加载数据，并储存到`沙盒`
        loadInfoForServer()
        //2.从沙盒判断是否有缓存
        let dicDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (dicDir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            //3.从 bundle 中读取json 用于`动态`设置访客视图图标
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]]
            else {
                return
        }
        //测试数据格式是否正确，转换成plist数据更直观
        // (array as NSArray).write(toFile: "/Users/abc/Desktop/demo.plist", atomically: true)
        //arrary -> json 序列化
        //Call can throw, but it is not marked with 'try' and the error is not handled
        // -> 多个错误是指需要使用do-catch 处理，try在单个错误中调用
        //            let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        //            (data as NSData).write(toFile: "/Users/abc/Desktop/main.json", atomically: true)
        
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典[clsName,title,imageName,visitorInfo]
    /// - Returns: 子控制器
    private func controller(dict: [String:Any]) -> UIViewController{
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            //通过反射 `NSClassFromString` (命名空间+类名)的方式获取类
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? ZQBaseViewController.Type,
            let  visitorDict = dict["visitorInfo"] as? [String:String]
            else {
                return UIViewController()
        }
        // 2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        //设置访客视图信息
        vc.visitorInfo = visitorDict
        // 3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        //添加图片并渲染.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected" )?.withRenderingMode(.alwaysOriginal)
        // 4. 设置 tabbar 的标题字体（大小）
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange],
                                             for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 12)],
                                             for: .normal)
        let nav = ZQBaseNavigationController.init(rootViewController: vc)
        
        return nav
    }
}


// MARK: - 模拟从服务器加载应用程序信息
extension ZQMainViewController{
    func loadInfoForServer(){
        //1. 模拟异步加载（此处暂定为加载已有的main.json）
//        DispatchQueue.main.async {
            //2.获取url
            let url = Bundle.main.url(forResource: "main.json", withExtension: nil)
            //3. >data
            let data = NSData(contentsOf: url!)
            print(data as Any)
            //3.写入磁盘
            // >获取沙盒路径,将data写入路径，以备下次使用
            let dicDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (dicDir as NSString).appendingPathComponent("main.json")
            data?.write(toFile: jsonPath, atomically: true)
//        }
        
    }
    
}
